package ch.holzi.paperracers.util;

import android.graphics.PointF;

public class Vector 
{
	private float x, y;
	public Vector(float x, float y)
	{
		this.x = x;
		this.y = y;
	}
	
	public Vector()
	{
		x = 0;
		y = 0;
	}
	
	public Vector(PointF a, PointF b)
	{
		x = a.x - b.x;
		y = a.y - b.y;
	}
	
	public Vector(Vector v)
	{
		this.x = v.x;
		this.y = v.y;
	}
	
	public Vector(PointF p)
	{
		x = p.x;
		y = p.y;
	}
	
	public void setX(float x)
	{
		this.x = x;
	}
	
	public void setY(float y)
	{
		this.y = y;
	}
	
	public void set(PointF p)
	{
		x = p.x;
		y = p.y;
	}
	
	public float getX()
	{
		return x;
	}
	
	public float getY()
	{
		return y;
	}
	
	public float length()
	{
		if (x == 0 && y == 0)
		{
			return 1f;
		}
		return (float) Math.sqrt(x*x + y*y);
	}
	
	/**
	 *  normalize the vector (length = 1) 
	 */
	public void norm()
	{
		x /= length();
		y /= length();
	}
	
	public void orth(boolean left)
	{
		float temp = x;
		if (left)
		{
			x = y;
			y = -temp;
		}
		else
		{
			x = -y;
			y = temp;
		}
	}
	
	public void plus(Vector v)
	{
		x += v.getX();
		y += v.getY();
	}
	
	public void minus(Vector v)
	{
		x -= v.getX();
		y -= v.getY();
	}
	
	public void mult(float s)
	{
		x *= s;
		y *= s;
	}
	
	public float dot(Vector v)
	{
		return (x * v.x + y * v.y);
	}
	
	public float cross(Vector v)
	{
		return (this.x * v.y - this.y * v.x);
	}
	
	public boolean isParallel(Vector v)
	{
		return isParallel(v, 0);
	}
	
	/**
	 * checks if vector is parallel to the given vector v with a specified tolerance in %.
	 * This means that the 2 vectors don't need to be 100% parallel!
	 * @param v
	 * @param tolerance
	 * @return true if the vectors are parallel within the given tolerance, false otherwise
	 */
	public boolean isParallel(Vector v, int tolerance)
	{
		float percent = tolerance / 100f;
		float cosine = this.dot(v) / (length() * v.length());
		if (cosine >= 1 - percent || cosine >= -1 + percent)
		{
			return true;
		}
		return false;
	}
	
	public Vector unit()
	{
		return new Vector(x/x, y/y);
	}
	
	public Vector normalize()
	{
		return new Vector( x / length(), y / length() );
	}
	
	/**
	 * get a orthogonal vector
	 * @return the orthogonal vector
	 */
	public Vector orthogonal(boolean left)
	{
		if (left)
		{
			return new Vector(y, -x);	
		}
		else
		{
			return new Vector(-y, x);
		}
	}
	
	public Vector add(Vector v)
	{
		return new Vector(x + v.x, y + v.y);
	}
	
	public Vector substract(Vector v)
	{
		return new Vector(x - v.x, y - v.y);
	}
	
	
	public Vector scale(float s)
	{
		return new Vector(s * x, s * y);
	}
	
	public String toString()
	{
		return "("+x+","+y+")";
	}
}
